﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using lycServo.cache;
using lycServo.dao;
using lycServo.entity;
using lycServo.handler;
using lycServo.init;

namespace lycServo
{
    public partial class FrmMain : Form
    {
        // 定义事件，用于传递消息
        //public event Action<string, string, string> ShowMessage;
        private readonly Dictionary<string, TextBox> show_dict = new Dictionary<string, TextBox>();
        public FrmMain()
        {
            InitializeComponent();
            InitUI();
        }

        #region ###UI###
        private void InitUI()
        {
            string unitSql = "select * from plc_unit where status=0";
            try
            {
                List<PlcUnitEntity> unitList = DBFactory.QueryList<PlcUnitEntity>(unitSql);
                if (unitList.Count < 1)
                {
                    MessageBox.Show("未检测到需要连接的设备!请检测[PLC_UNIT]中相关配置项");
                    Environment.Exit(Environment.ExitCode);
                    Dispose();
                    Close();
                }
                GlobalCachePool.plcUnits_dict.Add("wcs_servo", unitList);
                foreach (PlcUnitEntity unit in unitList)
                {
                    string unitNo = unit.UNIT_NO;
                    GlobalCachePool.single_unit_dict.Add(unitNo, unit);
                    TabPage page = new TabPage(unitNo)
                    {
                        Text = unitNo
                    };
                    //1.创建TextBox关联到page上
                    TextBox textBox = CreateTextControl(unitNo);
                    page.Controls.Add(textBox);
                    ServoTab.TabPages.Add(page);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("数据库连接异常!请检查连接配置!causeBy:" + ex.Message);
                Environment.Exit(Environment.ExitCode);
                Dispose();
                Close();
            }
        }
        #endregion

        #region ###生成组件###
        private TextBox CreateTextControl(string name)
        {
            FontFamily fontFamily = new FontFamily("楷体");
            TextBox tb = new TextBox
            {
                Name = name,
                Multiline = true,
                BorderStyle = BorderStyle.None,
                Dock = DockStyle.Fill,
                ScrollBars = ScrollBars.Both,
                Font = new Font(fontFamily, 9.5f)
            };
            show_dict.Add(name, tb);
            return tb;
        }
        #endregion

        #region ###信息展示###
        private void ShowMsgUpdate(string unitNo, string code, string msg)
        {
            //通过设备名称找到属于自己的TextBox
            if (show_dict.TryGetValue(unitNo, out TextBox showBox))
            {
                //使用委托的方式调用控件
                showBox.Invoke(new Action(() =>
                {
                    showBox.AppendText($"{DateTime.Now:yyyy-MM-dd HH:mm:ss.fff} >>> {code} {msg}" + Environment.NewLine);
                }));
            }
        }
        #endregion

        private void FrmMain_Load(object sender, EventArgs e)
        {
            //装载全局相关的信息,如全局PLC_ITEM，PLC_EVENT等
            InitLoading.InitServo("wcs_servo");
            //开启监听(由unit_no决定)
            if (GlobalCachePool.plcUnits_dict.TryGetValue("wcs_servo", out List<PlcUnitEntity> unitList))
            {
                foreach (PlcUnitEntity unit in unitList)
                {
                    ListenHandler listenHandler = new ListenHandler(unit.UNIT_NO, ShowMsgUpdate);
                    ThreadPool.QueueUserWorkItem(_ =>
                    {
                        listenHandler.StartListening();
                    });
                    ThreadPool.QueueUserWorkItem(_ =>
                    {
                        listenHandler.ListenChange();
                    });
                }
            }
        }

        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            DialogResult result = MessageBox.Show("确定要关闭伺服程序？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

            if (result == DialogResult.No)
            {
                e.Cancel = true;
            }
            else
            {
                Environment.Exit(Environment.ExitCode);
                Dispose();
                Close();
            }
        }
    }
}
